package com.njy.cloudalibaba.consumer.wrapper;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class SecretResponseWrapper extends HttpServletResponseWrapper {

    private PrintWriter printWriter;
    private ByteArrayOutputStream byteArrayOutputStream;

    public SecretResponseWrapper(HttpServletResponse response) {
        super(response);
        byteArrayOutputStream = new ByteArrayOutputStream();
        printWriter = new PrintWriter(byteArrayOutputStream);
    }

    public byte[] getResponseData()throws IOException{
        //将out、writer中的数据强制输出到WapperedResponse的buffer里面，否则取不到数据
        flushBuffer();
        return byteArrayOutputStream.toByteArray();
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return printWriter;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (printWriter!=null)
            printWriter.flush();
        if (byteArrayOutputStream != null)
            byteArrayOutputStream.flush();

    }

    /**
     * 响应结果会调用这个方法将内容写入byteArrayOutputStream
     * 在filter中调用getResponseData()方法获取请求的响应报文在filter进行加密
     * @return
     * @throws IOException
     */
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream() {
            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {

            }

            @Override
            public void write(int b) throws IOException {
                byteArrayOutputStream.write(b);
            }
        };
    }
}
